import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.image.PixelWriter;
import javafx.scene.image.WritableImage;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.scene.image.ImageView;
import javafx.stage.Stage;

public class homework_01 extends Application {

    @Override
    public void start(Stage primaryStage) {
        // 定义图像的宽度和高度
        int width = 800;
        int height = 800;

        // 创建一个可写的图像对象
        WritableImage image = new WritableImage(width, height);
        // 获取图像的像素写入器
        PixelWriter pixelWriter = image.getPixelWriter();

        // 定义斜线的起点和终点
        int x1 = 0;
        int y1 = 0;
        int x2 = 600;
        int y2 = 600;

        // 调用自定义的斜线绘制方法
        drawLineDDA(pixelWriter, x1, y1, x2, y2);

        // 创建一个 ImageView 来显示图像
        ImageView imageView = new ImageView(image);
        // 创建一个 StackPane 布局并将 ImageView 添加进去
        StackPane root = new StackPane(imageView);
        // 创建场景并将 StackPane 作为根节点
        Scene scene = new Scene(root, width, height);

        // 设置标题
        primaryStage.setTitle("Diagonal Line using DDA");
        // 将场景设置到舞台
        primaryStage.setScene(scene);
        // 显示舞台
        primaryStage.show();
    }

    // 自定义的 DDA 算法绘制直线方法
    private void drawLineDDA(PixelWriter pixelWriter, int x1, int y1, int x2, int y2) {
        int dx = x2 - x1;
        int dy = y2 - y1;
        int steps;

        if (Math.abs(dx) > Math.abs(dy)) {
            steps = Math.abs(dx);
        } else {
            steps = Math.abs(dy);
        }

        double xIncrement = (double) dx / (double) steps;
        double yIncrement = (double) dy / (double) steps;
        double x = x1;
        double y = y1;

        for (int i = 0; i <= steps; i++) {
            pixelWriter.setColor((int) Math.round(x), (int) Math.round(y), Color.BLACK);
            x += xIncrement;
            y += yIncrement;
        }
    }

    public static void main(String[] args) {
        // 启动 JavaFX 应用程序
        launch(args);
    }
}